<!-- 切换语言弹窗 -->
<template>
  <!-- <uv-picker
    ref="languagePickerRef"
    round="8"
    :columns="columns"
    :defaultIndex="defaultIndex"
    :immediateChange="true"
    @confirm="confirm"
    confirmColor="#FAB714"
    :visibleItemCount="6"
    :confirmText="currentLanguageTexts.confirm"
    :cancelText="currentLanguageTexts.cancel"
    v-if="placement === 'bottom'"
  ></uv-picker> -->
  <uv-popup ref="languagePickerRef" round="16rpx" custom-style="width: 50%">
    <view style="padding: 20rpx">
      <view
        style="
          text-align: center;
          line-height: 3;
          border-bottom: 2rpx solid #f5f5f5;
        "
        v-for="(item, index) in languageTypes"
        :key="item.key"
        @click="confirm({ indexs: [index] })"
        >{{ item.label }}</view
      >
    </view>
  </uv-popup>
</template>

<script setup>
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import { ref, watch, computed } from 'vue';

const props = defineProps({
  placement: {
    type: String,
    default: 'bottom',
  },
});

const defaultIndex = ref([0]);
const languagePickerRef = ref();
const mainStore = storeToRefs(useMainStore());
const { currentLanguage, currentLanguageTexts, languageTypes } = mainStore;

// const sys = uni.getSystemInfoSync();

const columns = computed(() => {
  return [[...languageTypes.value.map((el) => el.label), '']];
});

// 处理iOS Safari的特殊格式
// let defaultLanguage = '';
// if (sys.platform === 'ios') {
//   defaultLanguage = sys.language.replace(/_/g, '-');
// } else {
//   defaultLanguage = sys.language;
// }
// console.log('当前语言:', defaultLanguage);

// defaultLanguage = defaultLanguage.toLowerCase();
// if (!mainStore.isManualSetLang) {
//   // const defaultLanguage = navigator.language.toLowerCase()
//   if (
//     defaultLanguage.indexOf('cn') >= 0 ||
//     defaultLanguage.indexOf('zh') >= 0
//   ) {
//     mainStore.currentLanguage = languages[1];
//   } else if (defaultLanguage.indexOf('km') >= 0) {
//     mainStore.currentLanguage = languages[2];
//   } else {
//     mainStore.currentLanguage = languages[0];
//   }
// }

const confirm = ({ indexs }) => {
  console.log(languageTypes.value[indexs[0]]);
  currentLanguage.value = languageTypes.value[indexs[0]];
  mainStore.isManualSetLang = true;
  if (props.placement === 'center') {
    languagePickerRef.value.close();
  }
  location.reload();
};

const open = () => {
  languagePickerRef.value.open();
};

watch(
  () => currentLanguage.value,
  (nv) => {
    const index = columns.value[0].findIndex((el) => el === nv.label);
    defaultIndex.value = [index];
  }
);
defineExpose({
  open,
});
</script>

<style lang="scss" scoped></style>
